﻿package com.cbts.action.info;

import com.cbts.entity.Department;
import com.cbts.entity.TravelStandard;
import com.cbts.entity.UserGroup;
import com.cbts.entity.UserInfo;
import com.cbts.service.info.DepartmentService;
import com.cbts.service.info.UserInfoService;
import com.cbts.service.info.VerifierService;
import com.cbts.util.MD5Util;
import com.cbts.util.ObjectJsonValueProcessor;
import com.cbts.util.Page;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;

/**
 * @author 邱鸿辉
 *
 */
public class UserInfoAction extends ActionSupport{

	
	
	private static final long serialVersionUID = 1L;
	private UserInfoService userInfoService; 		//与员工管理相关服务
	private DepartmentService departmentService;	//与部门管理相关的服务
	private VerifierService verifierService;		//差旅审核修改的服务
	
	private UserGroup userGroup;					//用户组
	private List<UserGroup> userGroupList;			//用户组列表
	private UserInfo userInfo;						//员工
	private List<UserInfo> userInfoList;			//员工列表
	/*private int newUserGroupId;*/
	private String check;							//用户勾选的员工的userid组成的字符串
	private String operate;							//用户的操作：修改或者删除员工或者用户组
	private List<TravelStandard> travelStandardList;//差旅标准列表
	private String message;
	private File file;								//批量增加员工信息时上传的文件
	private String fileContentType;					//文件类型
	private String fileFileName;					//文件名
	private List<Department> departmentList;		//部门列表
	private String codeinput;						//验证码
	
	private String jsonResult;

	public String getJsonResult() {
		return jsonResult;
	}
	public void setJsonResult(String jsonResult) {
		this.jsonResult = jsonResult;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	
	public String getCodeinput() {
		return codeinput;
	}
	public void setCodeinput(String codeinput) {
		this.codeinput = codeinput;
	}
	public VerifierService getVerifierService() {
		return verifierService;
	}
	public void setVerifierService(VerifierService verifierService) {
		this.verifierService = verifierService;
	}
	public DepartmentService getDepartmentService() {
		return departmentService;
	}
	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}
	public List<Department> getDepartmentList() {
		return departmentList;
	}
	public void setDepartmentList(List<Department> departmentList) {
		this.departmentList = departmentList;
	}
	public List<TravelStandard> getTravelStandardList() {
		return travelStandardList;
	}
	public void setTravelStandardList(List<TravelStandard> travelStandardList) {
		this.travelStandardList = travelStandardList;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}

	public String getCheck() {
		return check;
	}
	public void setCheck(String check) {
		this.check = check;
	}
	public String getOperate() {
		return operate;
	}
	public void setOperate(String operate) {
		this.operate = operate;
	}
	public UserInfoService getUserInfoService() {
		return userInfoService;
	}
	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}
	/*public int getNewUserGroupId() {
		return newUserGroupId;
	}
	public void setNewUserGroupId(int newUserGroupId) {
		this.newUserGroupId = newUserGroupId;
	}*/
	public UserGroup getUserGroup() {
		return userGroup;
	}
	public void setUserGroup(UserGroup userGroup) {
		this.userGroup = userGroup;
	}
	public List<UserGroup> getUserGroupList() {
		return userGroupList;
	}
	public void setUserGroupList(List<UserGroup> userGroupList) {
		this.userGroupList = userGroupList;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}
	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}
	public List<UserInfo> getUserInfoList() {
		return userInfoList;
	}
	public void setUserInfoList(List<UserInfo> userInfoList) {
		this.userInfoList = userInfoList;
	}
	//增加一个员工
	public String addUserInfo(){
		HttpServletRequest request = ServletActionContext.getRequest();
		try{
			message = "";
			String hint = "";
			userInfo.setEmailValidated("否");//默认增加的员工的邮箱为未通过验证
			userInfo.setRegisterTime(new Date());//员工的注册时间，默认为增加时的时间
			userInfo.setCount(0.0);//员工所拥有的点数
			if(userInfo.getDepartment().getDepartmentId().equals(""))
				userInfo.setDepartment(null);
			if(userInfo.getUserGroup().getUserGroupId().equals(""))
				userInfo.setUserGroup(null);
			if(userInfoService.addUserInfo(userInfo))//调用service层的增加一个员工服务
				message = "增加员工成功";
			else
				message = "增加员工失败";
		}catch(Exception e){
			e.printStackTrace();
			message = "增加员工失败";
		}
			
		return "addinfo";
	}
	
	
	public String showUserInfoList(){
		HttpServletRequest request = ServletActionContext.getRequest();
		int page = 1;
		
		if(request.getParameter("page") != null)
			page = Integer.parseInt(request.getParameter("page"));
		
		JSONArray jsondata = new JSONArray();
		
		JSONObject jsonobject = new JSONObject();
		StringBuffer buffer = new StringBuffer();
		
		Page<UserInfo> userinfolist =  userInfoService.getAllUserInfo(page);
		
		List<Department> departmentlist = departmentService.getAllDepartmentByPage().getPageItems();
		departmentlist.add(new Department());
		List<UserGroup> usergrouplist = userInfoService.getAllUserGroupByPage().getPageItems();
		usergrouplist.add(new UserGroup());
		
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"businessTravels","registerTime","businessTravelListsForUserid",
				"businessTravelListsForVerifierId","applayReims","exchangeRecords"});
		config.registerJsonValueProcessor(Department.class, 
				new ObjectJsonValueProcessor(new String[]{"departmentId"}, Department.class));
		config.registerJsonValueProcessor(UserGroup.class, 
				new ObjectJsonValueProcessor(new String[]{"userGroupId"},UserGroup.class));
		
		JsonConfig depconfig = new JsonConfig();
		depconfig.setExcludes(new String[]{"handler","hibernateLazyInitializer","userInfos","departmentQuarterReports","departmentMonthReports"});
		JsonConfig ugconfig = new JsonConfig();
		ugconfig.setExcludes(new String[]{"handler","hibernateLazyInitializer","travelStandard","userInfos"});
		
		///
		jsondata = JSONArray.fromObject(departmentlist,depconfig);
		buffer.append("{\"departmentlist\":").append(jsondata.toString());
		jsondata = JSONArray.fromObject(usergrouplist,ugconfig);
		buffer.append(",\"userGrouplist\":").append(jsondata.toString());
		jsondata = JSONArray.fromObject(userinfolist.getPageItems(),config);
		buffer.append(",\"userlist\":").append(jsondata.toString());
		
		buffer.append(",\"pagenum\":").append(userinfolist.getPageNo());
		buffer.append(",\"pages\":").append(userinfolist.getTotalPageNum());
		buffer.append("}");
		jsonResult = buffer.toString();
		
		return "showinfolist";
		
	}
	
	public String addBatchUserInfo(){
		try{
			if(userInfoService.addBatchUserInfo(file,fileFileName))//调用service层的批量增加员工信息方法
				message = "增加员工成功";
			else 
				message = "增加员工失败";
			return "addsuccess";
		}catch(Exception e){
			e.printStackTrace();
			message = "增加员工失败";
			return "addinput";
		}
	}
	
	//增加一个用户组
	public String addUserGroup(){
		try{
			if(userInfoService.getUserGroupByUserGroupName(userGroup.getUserGroupName())!=null)
			{
				message = "用户组名已存在，增加失败";
				return ERROR;
			}
			if(userGroup.getTravelStandard().getStandardId() == null)
				userGroup.setTravelStandard(null);
			if(userInfoService.addUserGroup(userGroup))
				message = "增加用户组成功";
			else
			{
				message = "增加用户组失败";
				return ERROR;
			}
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			//message = "增加用户组失败";
			return INPUT;
		}
		
			
	
	}
	
	public String deleteUserGroup(){
		try{
			if(userGroup.getTravelStandard().getStandardId() == null)
				userGroup.setTravelStandard(null);
			if(userInfoService.deleteUserGroup(userGroup))
				message = "删除用户组成功";
			else
			{
				message = "删除用户组失败";
				return ERROR;
			}	
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			return INPUT;
		}
		
	}

	/*public String loadUserGroup(){
		userInfoService.getUserGroup(userGroup.getUserGroupId());
		return SUCCESS;
	}*/

	public String updateUserGroup(){
		try{
			if(userInfoService.sameUserGroupNameExist(userGroup.getUserGroupId(), userGroup.getUserGroupName()))
			{
				message = "用户组名已存在，修改失败";
				return ERROR;
			}
			if(userGroup.getTravelStandard().getStandardId() == null)
				userGroup.setTravelStandard(null);
			if(userInfoService.updateUserGroup(userGroup))
				message = "用户组修改成功";
			else
			{
				message = "用户组修改失败";
				return ERROR;
			}
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			return INPUT;
		}
		
	}
	/*public String moveToUserGroup()
	{
		return SUCCESS;
	}*/
	// 获取用户组列表，用于页面显示
	public String showUserGroupList(){
		try{
			userGroupList = userInfoService.getAllUserGroup();//获取所有的用户组
			travelStandardList = userInfoService.getAllTravelStandard();//获取所有的差旅标准
			travelStandardList.add(new TravelStandard());
			if(message != null)
			{
				ActionContext.getContext().put("message", message);
				message = null;
			}
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			return INPUT;
		}
				
		
	}
	/*public String getUserGroupUsers()
	{
		return SUCCESS;
	}*/
	public String login() {
		
		boolean b = false;
		ActionContext context = ActionContext.getContext();
		Map request = (Map) context.get("request");
		Map session=ServletActionContext.getContext().getSession();
		
		try {
			if (session.get("valcode")!=null&&
					codeinput.toLowerCase().equals(session.get("valcode").toString())) {
				if (userInfo!=null&&userInfo.getUserid()!=null&&userInfo.getPwd()!=null) {
					b = userInfoService.login(userInfo.getUserid(),userInfo.getPwd());
				}
				
				if(b == true){
					//userInfo.setPwd("");
					String userid=userInfo.getUserid();
					session.put("userid", userid);
					
					//lynn
					session.put("username", userInfoService.getUserInfo(userid).getUserName());
					if (userInfoService.getAllUserInfo().getPageItems()!=null) {
						session.put("usernumber", userInfoService.getAllUserInfo().getPageItems().size());
					}else {
						session.put("usernumber",0);
					}
					//将状态为待审核的条数放入session 
					if (verifierService.getBusinessTravelLists("待审核")!=null) {
						session.put("needCheck", verifierService.getBusinessTravelLists("待审核").size());
					}else {
						session.put("needCheck", 0);
					}
					
					//将状态为待报销的条数放入session 
					if (verifierService.getBusinessTravelLists("待报销")!=null) {
						session.put("needApplay", verifierService.getBusinessTravelLists("待报销").size());
					}else {
						
						session.put("needApplay", 0);
					}
	
					
					if(userInfoService.getUserInfo(userid).getAuthority().compareTo("管理员")==0)
						return "adminlogin";
					else
						return "stafflogin";
				}
					
				else
				{
					request.put("error", "账户名或密码错误");
					return "logfail";
				}
			}
			
			request.put("error", "请输入正确的验证码");
			return "logfail";
			
		} catch (Exception e) {
			e.printStackTrace();
			request.put("error", "账户名或密码错误");
			return "logfail";
		}
		
	}
	
	public String logout(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		if(session.getAttribute("userid")!=null){
			session.invalidate();
			return "logout";
		}else{
			return ERROR;
		}
	}
	
	public String updateOrDeleteUserInfo(){
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			
			String check = request.getParameter("check");
			String operatestring = request.getParameter("operate");
			int operate = Integer.parseInt(operatestring);
			
			String list = request.getParameter("list");
			System.out.println(list);
			//JSONObject jsonObject = JSONObject.fromObject(list);
			JSONArray jsonArray = JSONArray.fromObject(list);
			List<Map<String,Object>> mapJsonList = (List) jsonArray;
			
			List<UserInfo> userInfoList = new ArrayList<UserInfo>();
			if(operate == 1){	//删除
				for(int i=0;i < mapJsonList.size();i++){
					Map<String,Object> mapJson = mapJsonList.get(i);
					for(Entry<String,Object> entry : mapJson.entrySet()){
						Object strval = entry.getValue();
						String strkey = entry.getKey();
						
						UserInfo userinfo = new UserInfo();
						if(strkey.equals("userid")){
							userinfo.setUserid((String)strval);
							userInfoList.add(userinfo);
							break;
						}
					}
				}
			}else if(operate == 0){
				for(int i=0;i < mapJsonList.size();i++){
					Map<String,Object> mapJson = mapJsonList.get(i);
					
					UserInfo info = null;
					//创建一个userinfo
					for(Entry<String,Object> entry : mapJson.entrySet()){
						Object strval = entry.getValue();
						String strkey = entry.getKey();

						if(strkey.equals("userid")){
							info = userInfoService.getUserInfo((String)strval);
							break;
						}
					}
					
					for(Entry<String,Object> entry : mapJson.entrySet()){
						Object strval = entry.getValue();
						String strkey = entry.getKey();
						
						if(strkey.equals("userName"))
							info.setUserName((String)strval);
						if(strkey.equals("gender"))
							info.setGender((String)strval);
						if(strkey.equals("departmentId")){
							Department dep = departmentService.getDepartment((String)strval);
							info.setDepartment(dep);
						}
						if(strkey.equals("position"))
							info.setPosition((String)strval);
						if(strkey.equals("userGroupId")){
							UserGroup usergroup = userInfoService.getUserGroup(Integer.parseInt((String)strval));
							info.setUserGroup(usergroup);
						}
						if(strkey.equals("mail"))
							info.setEmail((String)strval);
						if(strkey.equals("authority"))
							info.setAuthority((String)strval);
					}
					userInfoList.add(info);
				}
			}

			userInfoService.updateOrDeleteUserInfo(userInfoList, null, operate);//调用service层的更新或者删除用户信息
		}catch(Exception e){
			e.printStackTrace();
		}
		return "updateinfo";
	}
	
	
}
